﻿#if _MSC_VER >= 1600
#pragma execution_character_set("utf-8")
#endif

#include "baiduocronline.h"
#include <QDebug>
#define sys_out qDebug()

BaiduOCROnline::BaiduOCROnline(QObject *parent) : QObject(parent)
{
    NetAccManager = new QNetworkAccessManager(this);
    https_ssl_config(NetRequest);
    NetRequest.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/x-www-form-urlencoded")); //接口固定
}

//配置https访问，win32依赖libcrypto-1_1.dll和libssl-1_1.dll，放在与exe同级目录下
void BaiduOCROnline::https_ssl_config(QNetworkRequest& NetworkRequest)
{
    QSslConfiguration config = NetworkRequest.sslConfiguration();
    config.setPeerVerifyMode(QSslSocket::VerifyNone);
    config.setProtocol(QSsl::TlsV1SslV3);
    NetworkRequest.setSslConfiguration(config);
}

//直接从QFile读取数据进行Base64编码，然后再进行urlencode
QString BaiduOCROnline::image2base64_str(const QString& imgpath)
{
    QByteArray data;
    QFile file(imgpath);
    if(!file.open(QIODevice::ReadOnly))
        return "";
    data = file.readAll();
    QString b64str = QString(data.toBase64().toPercentEncoding());//OCR识别要求base64编码后进行urlencode
    return b64str;
}

//QImage转base64编码字符串，弃用
QString BaiduOCROnline::image2base64_str(const QImage& img)
{
    QByteArray data;
    QBuffer buf(&data);
    buf.open(QIODevice::WriteOnly);
    img.save(&buf, "jpeg");//保存为jpeg格式
    QString b64str = QString(data.toBase64().toPercentEncoding());//OCR识别要求base64编码后进行urlencode
    return b64str;
}
//base64编码字符串转QImage，暂时无用
QImage BaiduOCROnline::base64_str2image(const QString & base64_str)
{
    QImage image;
    QByteArray base64_data = base64_str.toLatin1();
    image.loadFromData(QByteArray::fromBase64(base64_data));
    return image;
}

//获取AccToken
void BaiduOCROnline::getAccToken(const QString& API_Key, const QString& Secret_Key)
{
    if(API_Key.isEmpty() | Secret_Key.isEmpty())
    {
        QMessageBox::information(0,"提示","鉴权参数为空！");
        return;
    }
    //鉴权认证参考：http://ai.baidu.com/ai-doc/REFERENCE/Ck3dwjhhu
    QStringList parlist;
    parlist.append(QString("grant_type=%1").arg("client_credentials"));
    parlist.append(QString("client_id=%1").arg(API_Key));
    parlist.append(QString("client_secret=%1").arg(Secret_Key));
    QByteArray parameters = parlist.join("&").toUtf8();

    QUrl url("https://aip.baidubce.com/oauth/2.0/token");
    NetRequest.setUrl(url);
    connect(NetAccManager,&QNetworkAccessManager::finished,this,&BaiduOCROnline::getAccTokenReply);
    NetAccManager->post(NetRequest,parameters);
}
//获取AccToken槽
void BaiduOCROnline::getAccTokenReply(QNetworkReply* reply)
{
    if (reply->error() != QNetworkReply::NoError)
    {
        QMessageBox::warning(0, "请求错误！", reply->errorString());
        return;
    }
    else
    {
        QByteArray content = reply->readAll();
        reply->deleteLater();
        QJsonParseError jsonError;
        QJsonDocument doucment = QJsonDocument::fromJson(content, &jsonError);  // 转化为 JSON 文档
        if (!doucment.isNull() && (jsonError.error == QJsonParseError::NoError))
        {
            QJsonObject root_object = doucment.object();
            if(!root_object.contains("error"))
            {
                AccToken =  root_object.value("access_token").toString();  // 将 value 转化为字符串
                QMessageBox::information(0,"鉴权认证成功", AccToken);
            }
            else
            {
                QMessageBox::information(0,"鉴权认证失败", QString(doucment.toJson()));
            }
        }
    }
    disconnect(NetAccManager,&QNetworkAccessManager::finished,this,&BaiduOCROnline::getAccTokenReply);
}
//保存AccToken至txt文件，暂时无用
void BaiduOCROnline::writeAccToken(const QString& token)
{
    QFile f("AccToken.txt");
    if(!f.open(QIODevice::WriteOnly | QIODevice::Text))
    {
        qDebug() << ("无法打开AccToken.txt");
    }
    QTextStream txtOutput(&f);
    txtOutput << token;
}
//从txt文件读取AccToken，暂时无用
QString BaiduOCROnline::readAccToken()
{
    QFile f("AccToken.txt");
    if(!f.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        qDebug() << ("打开文件失败");
        return "";
    }
    QTextStream txtInput(&f);
    QString lineStr;
    lineStr = txtInput.readLine();
    f.close();
    return lineStr;
}
//标准OCR识别
void BaiduOCROnline::StdOCR(const QString& imagepath)
{
    QUrlQuery UrlQuery;
    UrlQuery.addQueryItem("access_token", AccToken);    //设置参数

    QUrl url(StdOCRUrl);
    url.setQuery(UrlQuery);
    NetRequest.setUrl(url);

    //图片base64转码
    QByteArray post_data = QString("image=" + image2base64_str(imagepath)).toUtf8();
    connect(NetAccManager,&QNetworkAccessManager::finished,this,&BaiduOCROnline::StdOCRReply);
    NetAccManager->post(NetRequest, post_data);
}
//标准OCR识别槽
void BaiduOCROnline::StdOCRReply(QNetworkReply* reply)
{
    if (reply->error() != QNetworkReply::NoError)
    {
        QMessageBox::warning(0, "请求错误！", reply->errorString());
        return;
    }
    else
    {
        QByteArray content = reply->readAll();
        QJsonParseError jsonError;
        QJsonDocument doucment = QJsonDocument::fromJson(content, &jsonError);  // 转化为 JSON 文档
        if (!doucment.isNull() && (jsonError.error == QJsonParseError::NoError))
        {
            QJsonObject root_object = doucment.object();
            if(!root_object.contains("error_msg"))
            {
                int words_result_num = root_object.take("words_result_num").toInt();
                QJsonArray words_result = root_object.take("words_result").toArray();
                QString OCRResult;
                for(int index = 0; index < words_result_num; index++)
                {
                    OCRResult.append(words_result.at(index).toObject().take("words").toString() + "\n");
                }
                emit StdOCRResult(OCRResult);
            }
            else
            {
                emit StdOCRResult(QString(doucment.toJson()));
            }
        }
        reply->deleteLater();
    }
    disconnect(NetAccManager,&QNetworkAccessManager::finished,this,&BaiduOCROnline::StdOCRReply);
}
//高精度OCR识别
void BaiduOCROnline::PreciseOCR(const QString& imagepath)
{
    QUrlQuery UrlQuery;
    UrlQuery.addQueryItem("access_token", AccToken);

    QUrl url(PreciseOCRUrl);
    url.setQuery(UrlQuery);
    NetRequest.setUrl(url);

    QByteArray post_data = QString("image=" + image2base64_str(imagepath)).toUtf8();
    connect(NetAccManager,&QNetworkAccessManager::finished,this,&BaiduOCROnline::PreciseOCRReply);
    NetAccManager->post(NetRequest, post_data);
}
//高精度OCR识别槽
void BaiduOCROnline::PreciseOCRReply(QNetworkReply* reply)
{
    if (reply->error() != QNetworkReply::NoError)
    {
        QMessageBox::warning(0, "请求错误！", reply->errorString());
        return;
    }
    else
    {
        QByteArray content = reply->readAll();
        QJsonParseError jsonError;
        QJsonDocument doucment = QJsonDocument::fromJson(content, &jsonError);  // 转化为 JSON 文档
        if (!doucment.isNull() && (jsonError.error == QJsonParseError::NoError))
        {
            QJsonObject root_object = doucment.object();
            if(!root_object.contains("error_msg"))
            {

                QJsonArray words_results = root_object.take("words_result").toArray();
                int results_count = words_results.size();
                QString OCRResult;
                for(int index = 0; index < results_count; index++)
                {
                    OCRResult.append(words_results.at(index).toObject().take("words").toString() + "\n");
                }
                emit PreciseOCRResult(OCRResult);
            }
            else
            {
                emit PreciseOCRResult(QString(doucment.toJson()));
            }
        }
        reply->deleteLater();
    }
    disconnect(NetAccManager,&QNetworkAccessManager::finished,this,&BaiduOCROnline::PreciseOCRReply);
}
//身份证件识别
void BaiduOCROnline::idCardScan(const QString& imagepath, quint8 id_card_side)
{
    QUrlQuery UrlQuery;
    UrlQuery.addQueryItem("access_token", AccToken);

    QUrl url(idCardUrl);
    url.setQuery(UrlQuery);
    NetRequest.setUrl(url);

    QString img_base64 = image2base64_str(imagepath);
    QByteArray post_data;
    if(id_card_side == id_card_fside)
    {
        post_data = QString("id_card_side=front&image=" + img_base64).toUtf8();
    }
    else
    {
        post_data = QString("id_card_side=back&image=" + img_base64).toUtf8();
    }
    connect(NetAccManager,&QNetworkAccessManager::finished,this,&BaiduOCROnline::idCardScanReply);
    NetAccManager->post(NetRequest, post_data);
}
//身份证件识别槽
void BaiduOCROnline::idCardScanReply(QNetworkReply* reply)
{
    if (reply->error() != QNetworkReply::NoError)
    {
        QMessageBox::warning(0, "请求错误！", reply->errorString());
        return;
    }
    else
    {
        QByteArray content = reply->readAll();
        QJsonParseError jsonError;
        QJsonDocument doucment = QJsonDocument::fromJson(content, &jsonError);  // 转化为 JSON 文档
        if (!doucment.isNull() && (jsonError.error == QJsonParseError::NoError))
        {
            if(!doucment.object().contains("error_msg"))
            {
                QJsonObject result_object = doucment.object().take("words_result").toObject();
                quint8 num = result_object.size();
                QStringList keys = result_object.keys();
                QString OCRResult;
                for(quint8 index = 0; index < num; index++)
                {
                    OCRResult.append(keys.at(index) + "：" + result_object.take(keys.at(index)).toObject().take("words").toString() + "\n");
                }
                emit idCardScanResult(OCRResult);
            }
            else
            {
                emit idCardScanResult(QString(doucment.toJson()));
            }
        }
        reply->deleteLater();
    }
    disconnect(NetAccManager,&QNetworkAccessManager::finished,this,&BaiduOCROnline::idCardScanReply);
}
//银行卡
void BaiduOCROnline::bankCardScan(const QString& imagepath)
{
    QUrlQuery UrlQuery;
    UrlQuery.addQueryItem("access_token", AccToken);

    QUrl url(bankCardUrl);
    url.setQuery(UrlQuery);
    NetRequest.setUrl(url);

    connect(NetAccManager,&QNetworkAccessManager::finished,this,&BaiduOCROnline::bankCardScanReply);
    QByteArray post_data = ("image=" + image2base64_str(imagepath)).toUtf8();
    NetAccManager->post(NetRequest, post_data);
}
void BaiduOCROnline::bankCardScanReply(QNetworkReply* reply)
{
    if (reply->error() != QNetworkReply::NoError)
    {
        QMessageBox::warning(0, "请求错误！", reply->errorString());
        return;
    }
    else
    {
        QByteArray content = reply->readAll();
        QJsonParseError jsonError;
        QJsonDocument doucment = QJsonDocument::fromJson(content, &jsonError);  // 转化为 JSON 文档
        if (!doucment.isNull() && (jsonError.error == QJsonParseError::NoError))
        {
            if(!doucment.object().contains("error_msg"))
            {
                QJsonObject result = doucment.object().take("result").toObject();
                QString OCRResult;
                OCRResult.append("银行名称：" + result.value("bank_name").toString());
                OCRResult.append("\n银行卡号：" + result.value("bank_card_number").toString());
                OCRResult.append("\n银行卡类型：" + QString::number( result.value("bank_card_type").toInt()));
                OCRResult.append("\n有效期：" + result.value("valid_date").toString());
                emit bankCardScanResult(OCRResult);
            }
            else
            {
                emit bankCardScanResult(QString(doucment.toJson()));
            }
        }
        reply->deleteLater();
    }
    disconnect(NetAccManager,&QNetworkAccessManager::finished,this,&BaiduOCROnline::bankCardScanReply);
}
//驾驶证
void BaiduOCROnline::driveCardScan(const QString& imagepath)
{
    QUrlQuery UrlQuery;
    UrlQuery.addQueryItem("access_token", AccToken);

    QUrl url(driveCardUrl);
    url.setQuery(UrlQuery);
    NetRequest.setUrl(url);

    QByteArray post_data = ("image=" + image2base64_str(imagepath)).toUtf8();
    connect(NetAccManager,&QNetworkAccessManager::finished,this,&BaiduOCROnline::driveCardScanReply);
    NetAccManager->post(NetRequest, post_data);
}
void BaiduOCROnline::driveCardScanReply(QNetworkReply* reply)
{
    if (reply->error() != QNetworkReply::NoError)
    {
        QMessageBox::warning(0, "请求错误！", reply->errorString());
        return;
    }
    else
    {
        QByteArray content = reply->readAll();
        QJsonParseError jsonError;
        QJsonDocument doucment = QJsonDocument::fromJson(content, &jsonError);  // 转化为 JSON 文档

        if (!doucment.isNull() && (jsonError.error == QJsonParseError::NoError))
        {

            if(!doucment.object().contains("error_msg"))
            {
                QJsonObject result = doucment.object().take("words_result").toObject();
                QString OCRResult;
                OCRResult.append("姓名：" + result.value("姓名").toObject().value("words").toString());
                OCRResult.append("\n性别：" + result.value("性别").toObject().value("words").toString());
                OCRResult.append("\n国籍：" + result.value("国籍").toObject().value("words").toString());
                OCRResult.append("\n出生日期：" + result.value("出生日期").toObject().value("words").toString());
                OCRResult.append("\n住址：" + result.value("住址").toObject().value("words").toString());
                OCRResult.append("\n初次领证日期：" + result.value("初次领证日期").toObject().value("words").toString());
                OCRResult.append("\n证号：" + result.value("证号").toObject().value("words").toString());
                OCRResult.append("\n准驾车型：" + result.value("准驾车型").toObject().value("words").toString());
                OCRResult.append("\n有效期限：" + result.value("有效期限").toObject().value("words").toString());
                OCRResult.append(" 至 " + result.value("至").toObject().value("words").toString());
                emit driveCardScanResult(OCRResult);
            }
            else
            {
                emit driveCardScanResult(QString(doucment.toJson()));
            }
        }
        reply->deleteLater();
    }
    disconnect(NetAccManager,&QNetworkAccessManager::finished,this,&BaiduOCROnline::driveCardScanReply);
}
//行驶证
void BaiduOCROnline::vehicleCardScan(const QString& imagepath)
{
    QUrlQuery UrlQuery;
    UrlQuery.addQueryItem("access_token", AccToken);

    QUrl url(vehicleCardUrl);
    url.setQuery(UrlQuery);
    NetRequest.setUrl(url);

    QByteArray post_data = ("image=" + image2base64_str(imagepath)).toUtf8();
    connect(NetAccManager,&QNetworkAccessManager::finished,this,&BaiduOCROnline::vehicleCardScanReply);
    NetAccManager->post(NetRequest, post_data);
}
void BaiduOCROnline::vehicleCardScanReply(QNetworkReply* reply)
{
    if (reply->error() != QNetworkReply::NoError)
    {
        QMessageBox::warning(0, "请求错误！", reply->errorString());
        return;
    }
    else
    {
        QByteArray content = reply->readAll();
        QJsonParseError jsonError;
        QJsonDocument doucment = QJsonDocument::fromJson(content, &jsonError);  // 转化为 JSON 文档

        if (!doucment.isNull() && (jsonError.error == QJsonParseError::NoError))
        {
            if(!doucment.object().contains("error_msg"))
            {
                QJsonObject result = doucment.object().take("words_result").toObject();
                QString OCRResult;
                OCRResult.append("所有人：" + result.value("所有人").toObject().value("words").toString());
                OCRResult.append("\n住址：" + result.value("住址").toObject().value("words").toString());
                OCRResult.append("\n车辆识别代号：" + result.value("车辆识别代号").toObject().value("words").toString());
                OCRResult.append("\n发动机号码：" + result.value("发动机号码").toObject().value("words").toString());
                OCRResult.append("\n车辆类型：" + result.value("车辆类型").toObject().value("words").toString());
                OCRResult.append("\n品牌型号：" + result.value("品牌型号").toObject().value("words").toString());
                OCRResult.append("\n使用性质：" + result.value("使用性质").toObject().value("words").toString());
                OCRResult.append("\n号牌号码：" + result.value("号牌号码").toObject().value("words").toString());
                OCRResult.append("\n注册日期：" + result.value("注册日期").toObject().value("words").toString());
                OCRResult.append("\n发证日期：" + result.value("发证日期").toObject().value("words").toString());
                OCRResult.append("\n发证单位：" + result.value("发证单位").toObject().value("words").toString());
                emit vehicleCardScanResult(OCRResult);
            }
            else
            {
                emit vehicleCardScanResult(QString(doucment.toJson()));
            }
        }
        reply->deleteLater();
    }
    disconnect(NetAccManager,&QNetworkAccessManager::finished,this,&BaiduOCROnline::vehicleCardScanReply);
}
//车牌识别
void BaiduOCROnline::licensePlateScan(const QString& imagepath)
{
    QUrlQuery UrlQuery;
    UrlQuery.addQueryItem("access_token", AccToken);

    QUrl url(licensePlateUrl);
    url.setQuery(UrlQuery);
    NetRequest.setUrl(url);

    QByteArray post_data = ("image=" + image2base64_str(imagepath) + "&multi_detect=true&multi_scale=true").toUtf8();
    connect(NetAccManager,&QNetworkAccessManager::finished,this,&BaiduOCROnline::licensePlateScanReply);
    NetAccManager->post(NetRequest, post_data);
}
void BaiduOCROnline::licensePlateScanReply(QNetworkReply* reply)
{
    if (reply->error() != QNetworkReply::NoError)
    {
        QMessageBox::warning(0, "请求错误！", reply->errorString());
        return;
    }
    else
    {
        QByteArray content = reply->readAll();
        QJsonParseError jsonError;
        QJsonDocument doucment = QJsonDocument::fromJson(content, &jsonError);  // 转化为 JSON 文档

        if (!doucment.isNull() && (jsonError.error == QJsonParseError::NoError))
        {
            QJsonObject root_object = doucment.object();
            if(!root_object.contains("error_msg"))
            {
                QJsonArray words_result = root_object.value("words_result").toArray();
                QJsonObject sub_object;
                QString OCRResult;
                for(int index = 0; index < words_result.size(); index++)
                {
                    sub_object = words_result.at(index).toObject();
                    OCRResult.append("牌号：" + sub_object.value("number").toString() + "，");
                    OCRResult.append("颜色：" + sub_object.value("color").toString() + "\n");
                }
                emit licensePlateScanResult(OCRResult);
            }
            else
            {
                emit licensePlateScanResult(QString(doucment.toJson()));
            }
        }
        reply->deleteLater();
    }
    disconnect(NetAccManager,&QNetworkAccessManager::finished,this,&BaiduOCROnline::licensePlateScanReply);
}
//增值税发票
void BaiduOCROnline::vat_invoiceScan(const QString& imagepath)
{
    QUrlQuery UrlQuery;
    UrlQuery.addQueryItem("access_token", AccToken);

    QUrl url(vat_invoicedUrl);
    url.setQuery(UrlQuery);
    NetRequest.setUrl(url);

    connect(NetAccManager,&QNetworkAccessManager::finished,this,&BaiduOCROnline::vat_invoiceScanReply);
    QByteArray post_data = ("image=" + image2base64_str(imagepath)).toUtf8();
    NetAccManager->post(NetRequest, post_data);
}
void BaiduOCROnline::vat_invoiceScanReply(QNetworkReply* reply)
{
    if (reply->error() != QNetworkReply::NoError)
    {
        QMessageBox::warning(0, "请求错误！", reply->errorString());
        return;
    }
    else
    {
        QByteArray content = reply->readAll();
        QJsonParseError jsonError;
        QJsonDocument doucment = QJsonDocument::fromJson(content, &jsonError);  // 转化为 JSON 文档

        if (!doucment.isNull() && (jsonError.error == QJsonParseError::NoError))
        {
            QJsonObject root_object = doucment.object();
            if(!root_object.contains("error_msg"))
            {
                QJsonObject words_result = root_object.value("words_result").toObject();
                QString OCRResult;
                OCRResult.append("发票种类：" +  words_result.value("InvoiceType").toString());
                OCRResult.append("\n发票名称：" +  words_result.value("InvoiceTypeOrg").toString());
                OCRResult.append("\n发票代码：" +  words_result.value("InvoiceCode").toString());
                OCRResult.append("\n发票代码的辅助校验码：" +  words_result.value("InvoiceCodeConfirm").toString());
                OCRResult.append("\n发票号码：" +  words_result.value("InvoiceNum").toString());
                OCRResult.append("\n发票号码的辅助校验码：" +  words_result.value("InvoiceNumConfirm").toString());
                OCRResult.append("\n机打号码：" +  words_result.value("MachineNum").toString());
                OCRResult.append("\n机器编号：" +  words_result.value("MachineCode").toString());
                OCRResult.append("\n校验码：" +  words_result.value("CheckCode").toString());
                OCRResult.append("\n开票日期：" +  words_result.value("InvoiceDate").toString());
                OCRResult.append("\n购方名称：" +  words_result.value("PurchaserName").toString());
                OCRResult.append("\n购方纳税人识别号：" +  words_result.value("PurchaserRegisterNum").toString());
                OCRResult.append("\n购方地址及电话：" +  words_result.value("PurchaserAddress").toString());
                OCRResult.append("\n购方开户行及账号：" +  words_result.value("PurchaserBank").toString());
                OCRResult.append("\n密码区：" +  words_result.value("Password").toString());
                OCRResult.append("\n省：" +  words_result.value("Province").toString());
                OCRResult.append("\n市：" +  words_result.value("City").toString());
                OCRResult.append("\n联次：" +  words_result.value("SheetNum").toString());
                OCRResult.append("\n是否代开：" +  words_result.value("Agent").toString());
                OCRResult.append("\n货物名称：" +  words_result.value("CommodityName").toArray().at(0).toObject().value("word").toString());
                OCRResult.append("\n规格型号：" +  words_result.value("CommodityType").toArray().at(0).toObject().value("word").toString());
                OCRResult.append("\n单位：" +  words_result.value("CommodityUnit").toArray().at(0).toObject().value("word").toString());
                OCRResult.append("\n数量：" +  words_result.value("CommodityNum").toArray().at(0).toObject().value("word").toString());
                OCRResult.append("\n单价：" +  words_result.value("CommodityPrice").toArray().at(0).toObject().value("word").toString());
                OCRResult.append("\n金额：" +  words_result.value("CommodityAmount").toArray().at(0).toObject().value("word").toString());
                OCRResult.append("\n税率：" +  words_result.value("CommodityTaxRate").toArray().at(0).toObject().value("word").toString());
                OCRResult.append("\n税额：" +  words_result.value("CommodityTax").toArray().at(0).toObject().value("word").toString());
                OCRResult.append("\n销售方名称：" +  words_result.value("SellerName").toString());
                OCRResult.append("\n销售方纳税人识别号：" +  words_result.value("SellerRegisterNum").toString());
                OCRResult.append("\n销售方地址及电话：" +  words_result.value("SellerAddress").toString());
                OCRResult.append("\n销售方开户行及账号：" +  words_result.value("SellerBank").toString());
                OCRResult.append("\n合计金额：" +  words_result.value("TotalAmount").toString());
                OCRResult.append("\n合计税额：" +  words_result.value("TotalTax").toString());
                OCRResult.append("\n价税合计(大写)：" +  words_result.value("AmountInWords").toString());
                OCRResult.append("\n价税合计(小写)：" +  words_result.value("AmountInFiguers").toString());
                OCRResult.append("\n收款人：" +  words_result.value("Payee").toString());
                OCRResult.append("\n复核：" +  words_result.value("Checker").toString());
                OCRResult.append("\n开票人：" +  words_result.value("NoteDrawer").toString());
                OCRResult.append("\n备注：" +  words_result.value("Remarks").toString());

                emit vat_invoiceScanResult(OCRResult);
            }
            else
            {
                emit vat_invoiceScanResult(QString(doucment.toJson()));
            }
        }
        reply->deleteLater();
    }
    disconnect(NetAccManager,&QNetworkAccessManager::finished,this,&BaiduOCROnline::vat_invoiceScanReply);
}

//定额发票
void BaiduOCROnline::quota_invoiceScan(const QString& imagepath)
{
    QUrlQuery UrlQuery;
    UrlQuery.addQueryItem("access_token", AccToken);

    QUrl url(quota_invoicedUrl);
    url.setQuery(UrlQuery);
    NetRequest.setUrl(url);

    connect(NetAccManager,&QNetworkAccessManager::finished,this,&BaiduOCROnline::quota_invoiceScanReply);
    QByteArray post_data = ("image=" + image2base64_str(imagepath)).toUtf8();
    NetAccManager->post(NetRequest, post_data);
}
void BaiduOCROnline::quota_invoiceScanReply(QNetworkReply* reply)
{
    if (reply->error() != QNetworkReply::NoError)
    {
        QMessageBox::warning(0, "请求错误！", reply->errorString());
        return;
    }
    else
    {
        QByteArray content = reply->readAll();
        QJsonParseError jsonError;
        QJsonDocument doucment = QJsonDocument::fromJson(content, &jsonError);  // 转化为 JSON 文档

        if (!doucment.isNull() && (jsonError.error == QJsonParseError::NoError))
        {
            QJsonObject root_object = doucment.object();
            if(!root_object.contains("error_msg"))
            {
                QJsonObject words_result = root_object.value("words_result").toObject();
                QString OCRResult;
                OCRResult.append("省：" +  words_result.value("province").toString());
                OCRResult.append("\n市：" +  words_result.value("city").toString());
                OCRResult.append("\n发票代码：" +  words_result.value("invoice_code").toString());
                OCRResult.append("\n发票号码：" +  words_result.value("invoice_number").toString());
                OCRResult.append("\n发票所在地：" +  words_result.value("location").toString());
                OCRResult.append("\n金额：" +  words_result.value("invoice_rate").toString());
                OCRResult.append("\n金额小写：" +  words_result.value("invoice_rate_lowercase").toString());
                emit quota_invoiceScanResult(OCRResult);
            }
            else
            {
                emit quota_invoiceScanResult(QString(doucment.toJson()));
            }
        }
        reply->deleteLater();
    }
    disconnect(NetAccManager,&QNetworkAccessManager::finished,this,&BaiduOCROnline::quota_invoiceScanReply);
}
//户口本识别

void BaiduOCROnline::family_bookScan(const QString& imagepath)
{
    QUrlQuery UrlQuery;
    UrlQuery.addQueryItem("access_token", AccToken);

    QUrl url(family_bookUrl);
    url.setQuery(UrlQuery);
    NetRequest.setUrl(url);

    connect(NetAccManager,&QNetworkAccessManager::finished,this,&BaiduOCROnline::family_bookScanReply);
    QByteArray post_data = ("image=" + image2base64_str(imagepath)).toUtf8();
    NetAccManager->post(NetRequest, post_data);
}
void BaiduOCROnline::family_bookScanReply(QNetworkReply* reply)
{
    if (reply->error() != QNetworkReply::NoError)
    {
        QMessageBox::warning(0, "请求错误！", reply->errorString());
        return;
    }
    else
    {
        QByteArray content = reply->readAll();
//        sys_out<<content;
//        emit vat_invoiceScanResult(content);
        QJsonParseError jsonError;
        QJsonDocument doucment = QJsonDocument::fromJson(content, &jsonError);  // 转化为 JSON 文档
        if(!doucment.isNull() && (jsonError.error == QJsonParseError::NoError))
        {
            QJsonObject root_object = doucment.object();
            if(root_object.value("words_result_num").toInt() == 0)
            {
                sys_out<<root_object.value("words_result_num").toInt();
//                emit family_bookScanError(QString(doucment.toJson()));
                emit family_bookScanError("识别错误，图片中未发现户口簿");
                emit family_bookScanError(content);
            }
            else
            {
                QJsonObject words_result = root_object.take("words_result").toObject();
                QMap<QString, QString> OCRResult;

                OCRResult.insert("Name", "");
                OCRResult.insert("Sex", "");
                OCRResult.insert("Nation", "");
                OCRResult.insert("CardNo", "");
                OCRResult.insert("Relationship", "");

                bool ret = words_result.contains("Name");
                if(ret)   //姓名
                {
                    QString result = words_result.value("Name").toObject().value("words").toString();
                    OCRResult.insert("Name", result);
                    sys_out<<"find Name:"<<result;
                }
                ret = words_result.contains("Sex");
                if(ret)    //性别
                {
                    QString result = words_result.value("Sex").toObject().value("words").toString();
                    OCRResult.insert("Sex", result);
                }
                ret = words_result.contains("Nation");
                if(ret) //民族
                {
                    QString result = words_result.value("Nation").toObject().value("words").toString();
                    OCRResult.insert("Nation", result);
                }
                else
                ret = words_result.contains("CardNo");
                if(ret) //身份证号
                {
                    QString result = words_result.value("CardNo").toObject().value("words").toString();
                    OCRResult.insert("CardNo", result);
                }
                ret = words_result.contains("Relationship");
                if(ret)   //与户主关系
                {
                    QString result = words_result.value("Relationship").toObject().value("words").toString();
                    OCRResult.insert("Relationship", result);
                }
                emit family_bookScanResult(OCRResult);
            }
        }
        reply->deleteLater();
    }
    disconnect(NetAccManager,&QNetworkAccessManager::finished,this,&BaiduOCROnline::family_bookScanReply);
    emit family_bookGoOn();
}
